package delivery

import (
	"encoding/json"
	"fmt"
	"github.com/goravel/framework/facades"
	"goravel/app/models"
	"goravel/app/models/common"
	"goravel/packages/socket/servers"
)

type DeliveryService struct {
}

func (d *DeliveryService) MakeDeliveryMsg(my_order models.Order) {
	order := models.Order{}
	facades.Orm().Query().Model(&models.Order{}).Where("id=?", my_order.ID).With("Commoditys").With("Commoditys.Commodity").With("Paydetails").With("User").
		Find(&order)
	delivery := models.Delivery{}
	user := models.User{}
	facades.Orm().Query().Model(&models.User{}).Where("id=?", order.UserID).Find(&user)
	delivery.SiteID = order.SiteID
	delivery.UserID = order.UserID
	delivery.TicketID = order.Ticketcode
	delivery.State = "1"
	delivery.Address = user.Address
	delivery.Phone = user.Mobile
	delivery.OrderID = order.ID
	orderdescs := common.DeliveryData{}
	for _, commodity := range order.Commoditys {
		orderdesc := common.OrderDesc{}
		orderdesc.Image = commodity.Commodity.CommodityPic
		orderdesc.Price = commodity.Saleprice
		orderdesc.Count = commodity.Salenums
		orderdesc.Name = commodity.Commodity.CommodityName
		orderdescs = append(orderdescs, orderdesc)
	}
	delivery.Description = orderdescs
	facades.Orm().Query().Model(&models.Delivery{}).Create(&delivery)
	//将orderdescs转成json字符串
	orderdescs_json, _ := json.Marshal(delivery)
	orderdescs_str := fmt.Sprintf("%s", orderdescs_json)
	//发送通知消息
	servers.SendMessage2Group("1", "1", fmt.Sprintf("%d", order.SiteID), 5001, "小程序下单", &orderdescs_str)
}
